// $Id: server.c 100 2011-10-21 15:05:36Z cedric.shih@gmail.com $
/*
 * Copyright 2011 Cedric Shih (cedric dot shih at gmail dot com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <unistd.h>

#include <event.h>

#include "log.h"
#include "request.h"
#include "handler.h"
#include "sessions.h"

#include "server.h"

#define DEFAULT_READ_TIMEOUT 50
#define DEFAULT_WRITE_TIMEOUT 50

void niohttp_server_accept_cb(int fd, short event, void *arg);

struct niohttp_server *niohttp_server_new(struct event_base *evbase)
{
	int rc;
	struct niohttp_server *server;

	niohttp_debug("constructing");

	if (!(server = calloc(1, sizeof(*server)))) {
		rc = errno ? errno : -1;
		niohttp_error("calloc: %s", strerror(rc));
		goto finally;
	}

	TAILQ_INIT(&server->handlers);
	server->evbase = evbase;
	server->accept.fd = -1;

	niohttp_debug("creating session context");

	if (!(server->sessions = niohttp_sessions_new())) {
		rc = errno ? errno : -1;
		niohttp_error("failed to create session context");
		goto finally;
	}

	server->timeout.read = DEFAULT_READ_TIMEOUT;
	server->timeout.write = DEFAULT_WRITE_TIMEOUT;
	rc = 0;

finally:
	if (rc != 0) {
		niohttp_server_free(server);
		server = NULL;
		errno = rc;
	}
	return server;
}

void niohttp_server_free(struct niohttp_server *server)
{
	struct niohttp_session *entry;

	if (!server) {
		return;
	}

	niohttp_debug("destructing");

	while ((entry = RB_MIN(niohttp_session_tree,
			&server->sessions->tree))) {
		if (niohttp_session_close(entry)) {
			break;
		}
	}

	if (event_initialized(&server->accept.ev) &&
			event_pending(&server->accept.ev, EV_READ, NULL)) {
		event_del(&server->accept.ev);
	}

	if (server->accept.fd >= 0) {
		close(server->accept.fd);
		server->accept.fd = -1;
	}

	if (server->sessions) {
		niohttp_sessions_free(server->sessions);
	}

	niohttp_handler_list_clear(&server->handlers);
	free(server);
}

int niohttp_server_bind(struct niohttp_server *server,
		const char *address, unsigned short port)
{
	int rc, fd = 0, flag = 1;
	struct sockaddr_in addr;

	if (!server || !address) {
		rc = EINVAL;
		goto finally;
	}

	if (server->accept.fd >= 0) {
		niohttp_error("already bound");
		rc = EEXIST;
		goto finally;
	}

	niohttp_debug("binding on %s port %d", address, port);

	errno = 0;

	if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
		rc = errno ? errno : -1;
		niohttp_error("failed to request socket: %s", strerror(errno));
		goto finally;
	}

	if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0) {
		rc = errno ? errno : -1;
		niohttp_error("failed to set reuse flag: %s", strerror(errno));
		goto finally;
	}

	addr.sin_family = AF_INET; // host byte order
	addr.sin_port = htons(port); // short, network byte order
	addr.sin_addr.s_addr = inet_addr(address);
	memset(addr.sin_zero, '\0', sizeof addr.sin_zero);

	errno = 0;

	if(bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
		rc = errno ? errno : -1;
		niohttp_error("failed to bind socket on %s port %d: %s",
				address, port, strerror(errno));
		goto finally;
	}

	errno = 0;

	if(listen(fd, 1024) < 0) {
		rc = errno ? errno : -1;
		niohttp_error("failed to listen: %s", strerror(errno));
		goto finally;
	}

	niohttp_debug("accepting connections from socket: %d", fd);

	event_set(&server->accept.ev, fd, EV_READ|EV_PERSIST,
			niohttp_server_accept_cb, server);

	if (event_base_set(server->evbase, &server->accept.ev)) {
		rc = errno ? errno : -1;
		niohttp_error("failed to assign event base: %s", strerror(rc));
		goto finally;
	}

	if (event_add(&server->accept.ev, NULL)) {
		rc = errno ? errno : -1;
		niohttp_error("failed to add event: %s", strerror(rc));
		goto finally;
	}

	server->accept.fd = fd;
	rc = 0;

finally:
	if (rc != 0) {
		if (fd > 0) {
			close(fd);
		}
	}
	return rc;
}

void niohttp_server_accept_cb(int fd, short event, void *arg)
{
	int rc, sock;
	struct sockaddr_in s_in;
	socklen_t len;
	struct niohttp_server *server = arg;
	struct niohttp_session *session;

	len = sizeof(s_in);
	errno = 0;

	if ((sock = accept(fd, (struct sockaddr *)&s_in, &len)) < 0) {
		rc = errno ? errno : -1;
		niohttp_error("failed to accept socket: %s", strerror(rc));
		goto finally;
	}

	niohttp_debug("socket %d accepted from %s:%d", sock,
			inet_ntoa(s_in.sin_addr), ntohs(s_in.sin_port));

	if (evutil_make_socket_nonblocking(sock)) {
		rc = errno ? errno : -1;
		niohttp_error("failed to make socket non-blocking: %s",
				strerror(rc));
		goto finally;
	}

	if ((rc = niohttp_sessions_add(server->sessions, &session))) {
		niohttp_error("failed to add session: %s", strerror(rc));
		goto finally;
	}

	session->fd = sock;
	session->server = server;

	if ((rc = niohttp_session_start(session, &s_in))) {
		niohttp_error("failed to start session: %s", strerror(rc));
		goto finally;
	}

	rc = 0;

finally:
	if (rc != 0) {
		if (sock >= 0) {
			close(sock);
		}
	}
	return;
}

int niohttp_server_add_handler(struct niohttp_server *server,
		const char *pattern, niohttp_handler_cb cb, void *cbarg)
{
	int rc;
	struct niohttp_handler *handler;

	if ((handler = niohttp_handler_list_find(&server->handlers,
			pattern))) {
		rc = EEXIST;
		niohttp_error("already registered: %s", pattern);
		goto finally;
	}

	niohttp_debug("adding %s handler: %p", pattern, cb);

	if ((rc = niohttp_handler_list_add(&server->handlers,
			pattern, cb, cbarg))) {
		niohttp_error("failed to add handler '%s': %s", pattern,
				strerror(rc));
		goto finally;
	}

	rc = 0;

finally:
	return rc;
}

int niohttp_server_remove_handler(struct niohttp_server *server,
		const char *pattern)
{
	int rc;
	struct niohttp_handler *handler;

	if (!(handler = niohttp_handler_list_find(&server->handlers,
			pattern))) {
		rc = ENOENT;
		niohttp_error("already registered: %s", pattern);
		goto finally;
	}

	niohttp_debug("removing %s handler", pattern);

	niohttp_handler_list_del(&server->handlers, handler);
	rc = 0;

finally:
	return rc;
}
